package com.ruix.app.ui.stratum;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.desmond.parallaxviewpager.ListViewFragment;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.widget.SpringView;
import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.adapter.superadapter.IMulItemViewType;
import com.ruix.app.cache.CacheFactory;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.mapper.ActionMapper;
import com.ruix.app.mapper.ClasssDetailMapper;
import com.ruix.app.mapper.PostAutherMapper;
import com.ruix.app.mapper.PostCommentsMapper;
import com.ruix.app.mapper.PostsCardMapper;
import com.ruix.app.model.ClassDetail;
import com.ruix.app.model.Classes;
import com.ruix.app.model.Comment;
import com.ruix.app.model.PostAuther;
import com.ruix.app.model.PostsCard;
import com.ruix.app.model.User;
import com.ruix.app.network.CacheObserver;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.network.exception.NetworkUnusableException;
import com.ruix.app.network.exception.RequestApiException;
import com.ruix.app.network.exception.TokenExpiredException;
import com.ruix.app.ui.adapter.PracticalCommuniAdapter;
import com.ruix.app.util.LogUitl;
import com.ruix.app.util.ShareUtil;
import com.ruix.app.util.SoftInputUtil;
import com.ruix.app.util.ToastUtil;
import com.ruix.app.widget.SharePostDialog;
import com.ruix.app.widget.dialog.CommentDialog;
import com.ruix.app.widget.dialog.CommentPostDialog;
import com.ruix.app.widget.dialog.CopyCommentDialog;
import com.ruix.app.widget.dialog.DeleteCommentDialog;
import com.ruix.app.widget.dialog.CommonDialog;
import com.ruix.app.widget.dialog.DeletePostDialog;
import com.ruix.app.widget.dialog.PostAuthorInfoDialog;
import com.ruix.app.widget.dialog.ReportPostDialog;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import io.reactivex.disposables.Disposable;


/**
 * 实践
 */
public class MomentsListViewFragment extends ListViewFragment implements PracticalCommuniAdapter.PracticalCommuActionListenler, DeleteCommentDialog.DeleteCommentListener, DeletePostDialog.DeletePostListener {

    public static final String TAG = MomentsListViewFragment.class.getSimpleName();

    private Classes currentClasses;
    private ClassDetail classDetail;
    //    private PracticalCommuAdapter adapter;
    private PracticalCommuniAdapter adapter;

    private PopupWindow moreActionPop, commentPop, sharePop;
    private DeleteCommentDialog deleteCommentDialog;
    private PostAuthorInfoDialog authorInfoDialog;
    private CopyCommentDialog copyCommentDialog;
    private DeletePostDialog deletePostDialog;
    private ReportPostDialog reportPostDialog;
    //    private
    private ArrayList<PostsCard> posts;
    private SpringView springView;
    //    private ImageView pushPostBtn;
    private int LOAD_COUNT = 20;
    private boolean isRefershing;
    private  View noMessageView;
    private boolean addedFooterView;

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (RuiXConstant.NOTICE_CHANGE_SHARE_STATE.equals(intent.getAction())) {
                boolean shareAction = intent.getBooleanExtra("canshare", true);
                adapter.setCanShare(shareAction);
                adapter.notifyDataSetHasChanged();
            } else if (RuiXConstant.NOTICE_RELEASE_POST_SUCCESS.equals(intent.getAction())) {
                loadPostList(LOAD_COUNT, 0, false);
            } else if (RuiXConstant.NOTICE_MOMENTS_REFRESH_ACTION.equals(intent.getAction())) {
                refreshPostList();
            }
        }

    };


    public static Fragment newInstance(int position, Classes classes, ClassDetail classDetail) {
        MomentsListViewFragment fragment = new MomentsListViewFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_POSITION, position);
        args.putSerializable("classes", classes);
        args.putSerializable("classDetail", classDetail);
        fragment.setArguments(args);
        return fragment;
    }

    public MomentsListViewFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mPosition = getArguments().getInt(ARG_POSITION);
        currentClasses = (Classes) getArguments().getSerializable("classes");
        classDetail = (ClassDetail) getArguments().getSerializable("classDetail");


        View view = inflater.inflate(R.layout.fragment_list_view, container, false);

         noMessageView = inflater.inflate(R.layout.layout_item_no_message, null, false);

        mListView = (ListView) view.findViewById(R.id.listview);
        springView = (SpringView) view.findViewById(R.id.spring_view);
        springView.setGive(SpringView.Give.BOTTOM);
        springView.setType(SpringView.Type.FOLLOW);
        springView.setFooter(new DefaultFooter(this.getContext()));
        springView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
//                loadPostList(LOAD_COUNT, 0, false);
            }

            @Override
            public void onLoadmore() {
                if (isRefershing) {
                    onFinishToRefresh();
                }
                loadPostList(LOAD_COUNT, adapter.getCount(), false);
            }
        });
        springView.setEnable(false);
//        springView


        View placeHolderView = inflater.inflate(R.layout.header_placeholder, mListView, false);
        mListView.addHeaderView(placeHolderView); //占位
        setListViewOnScrollListener();
        setAdapter();


        registerReceivers();

        loadClassDetail();
        loadPostListByCache();
        loadPostList(LOAD_COUNT, 0, false);

        return view;
    }

    private void setAdapter() {
        if (getContext() == null) return;
        adapter = new PracticalCommuniAdapter(getContext(), null, new IMulItemViewType<PostsCard>() {
            @Override
            public int getViewTypeCount() {
                return 7;
            }

            @Override
            public int getItemViewType(int position, PostsCard postsCard) {
                return postsCard.getDisplayType().ordinal();
            }

            @Override
            public int getLayoutId(int viewType) {
                int layout = R.layout.item_posts_style_one;
                switch (viewType) {
                    case 0:
                        layout = R.layout.item_posts_style_one;
                        break;
                    case 1:
                        layout = R.layout.item_posts_style_pic_glide_one;
//                        layout = R.layout.item_posts_style_pic_one;
                        break;
                    case 2:
                        layout = R.layout.item_posts_style_pic_glide_two;
//                        layout = R.layout.item_posts_style_pic_two;
                        break;
                    case 3:
                        layout = R.layout.item_posts_style_pic_glide_three;
//                        layout = R.layout.item_posts_style_pic_three;
                        break;
                    case 4:
                        layout = R.layout.item_posts_style_pic_glide_four;
//                        layout = R.layout.item_posts_style_pic_four;
                        break;
                    case 5:
                        layout = R.layout.item_posts_style_pic_glide_five;
//                        layout = R.layout.item_posts_style_pic_five;
                        break;
                    case 6:
                        layout = R.layout.item_posts_style_pic_glide_seven;
//                        layout = R.layout.item_posts_style_pic_seven;
                        break;

                }
                return layout;
            }
        });
        adapter.setActivity((Activity) getContext());
        mListView.setAdapter(adapter);
        adapter.setActionListenler(this);
        if (classDetail != null) {
            adapter.setCanShare(classDetail.isCanSharePost());
            adapter.setFriendCircle(classDetail.isTeacherFriendCircle());
        }
    }


    private void loadPostList(int limit, final int offset, final boolean hasLoading) {
        if (currentClasses == null) {
            return;
        }
        RequestFactory.classPostList(currentClasses.getID(), limit, offset, new PostsCardMapper(), new RXObserver<ArrayList<PostsCard>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<PostsCard> value) {
                // TODO: 2017/4/2020
                if (value != null && value.size() > 0) {
                    if (offset > 0) {
                        if (posts != null) {
                            posts.addAll(value);
                        }
                        adapter.addAll(value);
                        springView.setEnable(true);
                        removeFooterView();
                    } else {
                        posts = value;
                        adapter.replaceAll(value);
                        if (value.size() < 20){ //
                            springView.setEnable(false);
                            addFooterView();
                        } else {
                            springView.setEnable(true);
                        }
                        CacheFactory.cachePostList(currentClasses.getID(), value);
                    }
                } else {
                    if (hasLoading) {
//                        showNoMessageTip();
                    } else {
                        showErrorTip("没有更多实践");
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                if (!hasLoading) {
                    springView.onFinishFreshAndLoad();
                }
            }

            @Override
            public void onComplete() {
                if (!hasLoading) {
                    springView.onFinishFreshAndLoad();
                }

            }
        });
    }

    private void addFooterView(){
        if (noMessageView != null) {
            addedFooterView = true;
            mListView.addFooterView(noMessageView);
        }
    }

    private void removeFooterView(){
        if (noMessageView != null && addedFooterView) {
            addedFooterView = false;
            mListView.removeFooterView(noMessageView);
        }
    }


    private void loadClassDetail() {
        if (currentClasses == null) {
            return;
        }
        RequestFactory.classDetail(currentClasses.getID(), new ClasssDetailMapper(currentClasses.getID()), new RXObserver<ClassDetail>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ClassDetail value) {
                classDetail = value;
                if (classDetail != null) {
                    adapter.setProhibited(classDetail.isProhibited());//
                    adapter.setCanShare(classDetail.isCanSharePost());
                    adapter.setFriendCircle(classDetail.isTeacherFriendCircle());
                    adapter.notifyDataSetHasChanged();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    public void showMoreActionDialog() {

    }

    public void showRelayVidwDialog() {

    }

    @Override
    public void deletePosts(PostsCard item, int position) {
        showDeletePostDialog(item.getID(), position);
    }

    @Override
    public void sharePosts(PostsCard item) {
        showSharePopupWindow(getView().getRootView(), item);
    }

    @Override
    public void commentPosts(PostsCard item, int position) {
        User user = UserManager.getCurrentUser();
        if (user != null && user.isProhibited()) {
            showErrorTip("你已被圈子禁言");
            return;
        }
//        showCommentPopupWindow(getView().getRootView(), item, null);
        showCommentDialog(item,null);
    }

    @Override
    public void moreActionPosts(PostsCard item) {
        showDialog(item.getID());
    }

    @Override
    public void praisePosts(PostsCard item, int position) {
//        ToastUtil.showSuccessMsg("点赞");
        item.addPraise();
//        adapter.notifyItemChanged(position);
        adapter.notifyDataSetHasChanged();
        //todo  requst
        praisePost(item.getID());
    }

    @Override
    public void unpraisePosts(PostsCard item, int position) {
//        ToastUtil.showSuccessMsg("取消点赞");
        item.canclePraise();
        adapter.notifyDataSetHasChanged();
//        adapter.notifyItemChanged(position);
//        adapter.notifyItemChanged(position,item);
        praisePost(item.getID());
    }

    @Override
    public void actionComment(PostsCard item, int commentPosition) {
        //点击
        ArrayList<Comment> comments = item.getComments();
        Comment comment = comments.get(commentPosition);
        String uid = UserManager.getCurrentUser().getID();
        if (comment.getAuthorId().equals(uid)) {
            showDeleteCommentDialog(item, commentPosition);
        } else {
            showCommentDialog(item,comment);
//            showCommentPopupWindow(getView().getRootView(), item, comment);
        }
    }

    @Override
    public void onLongClickComment(PostsCard item, int commentPosition) {
        ArrayList<Comment> comments = item.getComments();
        if (comments != null && comments.size() > commentPosition) {
            Comment comment = comments.get(commentPosition);
            String uid = UserManager.getCurrentUser().getID();
            if (comment.getAuthorId().equals(uid)) {
                showDeleteCommentDialog(item, commentPosition);
            } else {
                showCopyCommentDialog(comment.getContent());
            }
        }
    }

    @Override
    public void clickAvatar(PostsCard item, int position) {
        RequestFactory.postAuthorInfo(item.getID(), new PostAutherMapper(), new RXObserver<PostAuther>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(PostAuther value) {
                if (value != null) {
                    showPostAutherInfoDialog(value);
                }
            }

            @Override
            public void onError(Throwable e) {
                showErrorTip(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });


    }

    @Override
    public void onLongClickPost(PostsCard item, int commentPosition) {
        String words = item.getWords();
        if (!TextUtils.isEmpty(words)) {
            showCopyCommentDialog(words);
        }
    }

    //点赞 取消点赞
    private void praisePost(String id) {
        RequestFactory.likePosts(id, null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    //删除帖子
    private void deletePost(String postId, final int position) {

        RequestFactory.deletePosts(postId, new ActionMapper(), new RXObserver<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean value) {
                if (value) {
                    posts.remove(position);
                    adapter.remove(position);
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    //
    private void showDialog(String postId) {
        showMoreActionPopupWindow(getView().getRootView(), postId);
    }


    public void showMoreActionPopupWindow(View view, final String postId) {
        if (moreActionPop != null && moreActionPop.isShowing()) {
            moreActionPop.dismiss();
            moreActionPop = null;
        }

//        if (moreActionPop == null) {
        Activity activity = (Activity) getContext();
        View contentView = LayoutInflater.from(activity).inflate(
                R.layout.layout_posts_more, null);
        contentView.findViewById(R.id.btn_enjoy_pay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissMoreActionPopupWindow();
                showErrorTip("打赏功能即将上线");
            }
        });

        contentView.findViewById(R.id.btn_accuse_posts).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                    reportPosts(postId);
                showReportPostComfirmDialog(postId);
                dismissMoreActionPopupWindow();
            }
        });

        moreActionPop = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                (int) this.getResources().getDimension(R.dimen.h_w_96));
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = 0.6f;
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        activity.getWindow().setAttributes(lp);
        moreActionPop.setAnimationStyle(R.style.PopupWindowAnimation2);
        moreActionPop.setFocusable(true);
        moreActionPop.setBackgroundDrawable(new BitmapDrawable());
        moreActionPop.setOutsideTouchable(true);
        moreActionPop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        moreActionPop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
                Activity activity = (Activity) getContext();
                WindowManager.LayoutParams lp = activity.getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                activity.getWindow().setAttributes(lp);
                moreActionPop = null;
            }
        });
//        } else if (moreActionPop != null && !moreActionPop.isShowing()) {
//            // TODO: 2017/4/26
//            Activity activity = (Activity) getContext();
//            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
//            lp.alpha = 0.6f;
//            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
//            activity.getWindow().setAttributes(lp);
//            moreActionPop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
//        }
    }

    public void dismissMoreActionPopupWindow() {
        if (moreActionPop != null && moreActionPop.isShowing()) {
            moreActionPop.dismiss();
            moreActionPop = null;
        }
    }


    private void reportPosts(String postId) {
        RequestFactory.reportPost(postId, null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Object value) {
                showErrorTip("举报成功");
            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
            }

            @Override
            public void onComplete() {

            }
        });

    }

    private void showReportPostComfirmDialog(String postId) {
        if (reportPostDialog == null) {
            reportPostDialog = new ReportPostDialog(this.getContext());
            reportPostDialog.setListener(new ReportPostDialog.ReportPostListener() {
                @Override
                public void reportPostPositive(String postID) {
                    reportPosts(postID);
                }
            });
        }
        reportPostDialog.show(postId);
    }


    private void showCommentDialog(final PostsCard item, final Comment comment) {
        CommentDialog dialog =  CommentDialog.newInstance(this.getContext(),item,comment,new CommentDialog.CommentListener(){

            @Override
            public void submitCommentAction(String commentStr) {
                submitComment(item, comment, commentStr);
            }
        });
        dialog.show();
        dialog.initHint();
    }

    private void showCommentPopupWindow(View view, final PostsCard item, final Comment comment) {
        if (commentPop != null && commentPop.isShowing()) {
            commentPop.dismiss();
            commentPop = null;
        }

//        if (commentPop == null) {
        Activity activity = (Activity) getContext();
        View contentView = LayoutInflater.from(activity).inflate(
                R.layout.layout_circle_comment, null);
        final EditText editText = (EditText) contentView.findViewById(R.id.et_leave_words);
        editText.setTextIsSelectable(true);
        if (comment != null) {
            String name = comment.getAuthorName();
            if (!TextUtils.isEmpty(name)) {
                editText.setHint(String.format("回复：%s", name));
            }
        } else {
            if (!TextUtils.isEmpty(item.getUserName())) {
                editText.setHint(String.format("评论：%s", item.getUserName()));
            }
        }

        final TextView sendComment = (TextView) contentView.findViewById(R.id.tv_send_message);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    sendComment.setEnabled(true);
                } else {
                    sendComment.setEnabled(false);
                }
            }
        });
        sendComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String commentStrin = editText.getText().toString();
                if (!TextUtils.isEmpty(commentStrin)) {
                    dismissCommentPopupWindow();
                    submitComment(item, comment, commentStrin);
                } else {
                    showErrorTip("评论内容不能为空");
                }
            }
        });
        commentPop = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        commentPop.setFocusable(true);
        commentPop.setBackgroundDrawable(new BitmapDrawable());
        commentPop.setOutsideTouchable(true);
        commentPop.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        commentPop.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        commentPop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        commentPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                commentPop = null;
            }
        });
//            editText.requestFocus(); //// TODO: 2017/4/30

        SoftInputUtil.show(this.getActivity());
//        } else if (commentPop != null && !commentPop.isShowing()) {
//            commentPop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
//            SoftInputUtil.show(this.getActivity());
//        } else {
//            dismissCommentPopupWindow();
//        }
    }

    private void dismissCommentPopupWindow() {
        if (commentPop != null && commentPop.isShowing()) {
            commentPop.dismiss();
            commentPop = null;
        }
    }


    //评论
    private void submitComment(final PostsCard item, final Comment comment, String commentContent) {
        final Comment newComment = new Comment();
        if (comment != null) {
            newComment.setReplyID(comment.getAuthorId());
        }
        newComment.setContent(commentContent);
        RequestFactory.pushCommnet(item.getID(), newComment, null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {
                showErrorTip("提交成功");
                loadPostsComment(item);
                //
            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //获取评论
    private void loadPostsComment(final PostsCard item) {
        RequestFactory.classPostsDetail(item.getID(), new PostCommentsMapper(), new RXObserver<ArrayList<Comment>>() {
            @Override
            public void onSubscribe(Disposable d) {
                //post
            }

            @Override
            public void onNext(ArrayList<Comment> value) {
                item.repaceComments(value);
                adapter.notifyDataSetHasChanged();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    public void showSharePopupWindow(View view, final PostsCard item) {
        if (sharePop != null && sharePop.isShowing()) {
            sharePop.dismiss();
            sharePop = null;
        }

//        if (sharePop == null) {
            Activity activity = this.getActivity();
            View contentView = LayoutInflater.from(activity).inflate(
                    R.layout.dialog_share_post, null);
            contentView.findViewById(R.id.ll_share_to_wechat).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismissSharePopupWindow();
                    shareShit(item, true);
                }
            });

            contentView.findViewById(R.id.ll_share_to_circle).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismissSharePopupWindow();
                    shareShit(item, false);
                }
            });

            sharePop = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                    (int) this.getResources().getDimension(R.dimen.h_w_96));
            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
            lp.alpha = 0.6f;
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            activity.getWindow().setAttributes(lp);
            sharePop.setAnimationStyle(R.style.PopupWindowAnimation2);
            sharePop.setFocusable(true);
            sharePop.setBackgroundDrawable(new BitmapDrawable());
            sharePop.setOutsideTouchable(true);
            sharePop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
            sharePop.setOnDismissListener(new PopupWindow.OnDismissListener() {

                // 在dismiss中恢复透明度
                public void onDismiss() {
                    Activity activity = MomentsListViewFragment.this.getActivity();
                    WindowManager.LayoutParams lp = activity.getWindow()
                            .getAttributes();
                    lp.alpha = 1f;
                    activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    activity.getWindow().setAttributes(lp);
                    moreActionPop = null;
                }
            });
//        } else if (sharePop != null && !sharePop.isShowing()) {
//            // TODO: 2017/4/26
//            Activity activity = this.getActivity();
//            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
//            lp.alpha = 0.6f;
//            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
//            activity.getWindow().setAttributes(lp);
//            sharePop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
//        }
    }

    public void dismissSharePopupWindow() {
        if (sharePop != null && sharePop.isShowing()) {
            sharePop.dismiss();
            sharePop = null;
        }
    }


    private void showCopyCommentDialog(String comment) {
        if (copyCommentDialog == null) {
            copyCommentDialog = new CopyCommentDialog(getContext());
        }
        copyCommentDialog.show(comment);
    }

    private void showDeleteCommentDialog(PostsCard item, int commentPosition) {
        if (deleteCommentDialog == null) {
            deleteCommentDialog = new DeleteCommentDialog(this.getContext());
            deleteCommentDialog.setListener(this);
        }
        deleteCommentDialog.show(item, commentPosition);
    }


    private void deleteComment(final PostsCard item, final int commentPosition) {
        Comment comment = item.getComments().get(commentPosition);
        RequestFactory.deleteCommnet(comment.getID(), new ActionMapper(), new RXObserver<Boolean>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean value) {
                if (value) {
                    item.deleteComment(commentPosition);
                    adapter.notifyDataSetHasChanged();
                }

            }

            @Override
            public void onError(Throwable e) {
                showErrorTip(e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void deleteCommentPositive(PostsCard item, int commentPosition) {
        deleteComment(item, commentPosition);
    }

    public void showSuccessTip(String msg) {
        ToastUtil.showNewSuccessMsg(msg);
    }


    public void showErrorTip(String msg) {
        ToastUtil.showNewErrorMsg(msg);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceivers();
    }

    private void registerReceivers() {
        //TODO 只有班主任注册
        IntentFilter filter = new IntentFilter();
        filter.addAction(RuiXConstant.NOTICE_CHANGE_SHARE_STATE);
        filter.addAction(RuiXConstant.NOTICE_RELEASE_POST_SUCCESS);
        filter.addAction(RuiXConstant.NOTICE_MOMENTS_REFRESH_ACTION);
        getContext().registerReceiver(myReceiver, filter);
    }

    private void unregisterReceivers() {
        if (myReceiver != null) {
            getContext().unregisterReceiver(myReceiver);
        }
    }


    private void showPostAutherInfoDialog(PostAuther postAuther) {
        if (authorInfoDialog == null) {
            authorInfoDialog = new PostAuthorInfoDialog(this.getContext());
        }
        authorInfoDialog.show(postAuther);
        authorInfoDialog.setPostAuther(postAuther);
    }

    private void showDeletePostDialog(String id, int position) {
        if (deletePostDialog == null) {
            deletePostDialog = new DeletePostDialog(this.getContext());
            deletePostDialog.setListener(this);
        }
        deletePostDialog.show(id, position);
    }

    @Override
    public void deletePostPositive(String postID, int commentPosition) {
        deletePost(postID, commentPosition);
    }

    public void onFinishToRefresh() {
        isRefershing = false;
        Intent intent = new Intent(RuiXConstant.NOTICE_MOMENTS_REFRESH_FINISH);
        RuiApplication.getAppContext().sendBroadcast(intent);
    }

    private void refreshPostList() {
        if (currentClasses == null) {
            onFinishToRefresh();
            return;
        }
        if (springView != null) {
            springView.onFinishFreshAndLoad();
        }
        isRefershing = true;

        RequestFactory.classPostList(currentClasses.getID(), LOAD_COUNT, 0, new PostsCardMapper(), new RXObserver<ArrayList<PostsCard>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ArrayList<PostsCard> value) {
                if (value != null && value.size() > 0) {
                    if (posts != null && posts.size() > 0) {
//                        if (posts.get(0).getID().equals(value.get(0).getID())) {
//                            showErrorTip("没有新内容了，请稍后刷新");
//                        }
                        posts = value;
                        adapter.replaceAll(value);
                        CacheFactory.cachePostList(currentClasses.getID(), value);
                    }
                } else {
//                    showErrorTip("没有更多内容了");
                }
            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
                onFinishToRefresh();
            }

            @Override
            public void onComplete() {
                onFinishToRefresh();
            }
        });

    }


    private void loadPostListByCache() {
        if (currentClasses == null) {
            return;
        }
        CacheFactory.loadPostList(currentClasses.getID(), new CacheObserver<ArrayList<PostsCard>>() {
            @Override
            public void onNext(ArrayList<PostsCard> value) {
                if (value != null) {
                    posts = value;
                    adapter.replaceAll(value);
                }
            }
        });

    }


    public void resolveException(Throwable e) {
        if (e instanceof SocketTimeoutException) {
            showErrorTip("网络不通");
        } else if (e instanceof UnknownHostException) { //解析不到域名 网络不通
            showErrorTip("网络不通");
        } else if (e instanceof NetworkUnusableException) { // 网络不可用，比如WiFi断开
            showErrorTip("网络不通");
        } else if (e instanceof IOException) { //socket 超时 网络超时 SocketTimeoutException
            showErrorTip("网络不通");
        } else if (e instanceof TokenExpiredException) { //重新登录
            Intent intent = new Intent();
            intent.setAction(RuiXConstant.NOTICE_LOGOUT);
            RuiApplication.getAppContext().sendOrderedBroadcast(intent, null);
        } else if (e instanceof RequestApiException) {
            showErrorTip(e.getMessage());
        } else {

        }
    }


    private void shareShit(PostsCard postsCard, boolean firend) {
        String title = postsCard.getWords();
        String content = String.format("%s的主题", postsCard.getUserName());
        String webUrl = RuiXConstant.WX_SHARE_URL + postsCard.getEncryptId();
        if (title == null) {
            content = "";
        }
        if (content == null) {
            content = "";
        }
        if (firend) {
            ShareUtil.shareToTimeline(this.getActivity(), currentClasses.getIcon(), webUrl, title, content, null);
        } else {
            ShareUtil.shareToSession(this.getActivity(), currentClasses.getIcon(), webUrl, title, content, null);
        }
    }


}

